package com.kou.backend.service.impl.user;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kou.backend.bo.LoginLogExcelBO;
import com.kou.backend.dao.UserLoginLogDao;
import com.kou.backend.dto.user.SaveLoginLogDTO;
import com.kou.backend.entity.UserLoginLogDO;
import com.kou.backend.error.CommonErrorEnum;
import com.kou.backend.exception.CommonException;
import com.kou.backend.request.log.ExportLogReqDTO;
import com.kou.backend.request.log.LogLoginQueryListReqDTO;
import com.kou.backend.resposne.log.LogLoginListResponseDTO;
import com.kou.backend.service.UserLoginLogService;
import com.kou.backend.utils.DateUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Kou
 * @description 针对表【op_user_login_log(用户登录日志表)】的数据库操作Service实现
 * @createDate 2023-09-02 12:02:17
 */
@Service
public class UserLoginLogServiceImpl extends ServiceImpl<UserLoginLogDao, UserLoginLogDO>
        implements UserLoginLogService {

    @Resource
    private UserLoginLogDao userLoginLogDao;

    @Override
    public void saveLog(SaveLoginLogDTO loginLogDTO) {
        UserLoginLogDO loginLogDO = new UserLoginLogDO();
        BeanUtils.copyProperties(loginLogDTO, loginLogDO);
        userLoginLogDao.insert(loginLogDO);
    }

    @Override
    public PageInfo<LogLoginListResponseDTO> queryList(LogLoginQueryListReqDTO reqDTO) {
        PageHelper.startPage(reqDTO.getPageNum(), reqDTO.getPageSize());
        List<UserLoginLogDO> loginLogs = userLoginLogDao.queryList(reqDTO);

        PageInfo pageInfo = PageInfo.of(loginLogs);
        //构造返参列表
        List<LogLoginListResponseDTO> responseDTOList = loginLogs.stream().map(item -> {
            LogLoginListResponseDTO responseDTO = new LogLoginListResponseDTO();
            BeanUtils.copyProperties(item, responseDTO);
            return responseDTO;
        }).collect(Collectors.toList());
        pageInfo.setList(responseDTOList);

        return pageInfo;
    }

    @Override
    public void export(ExportLogReqDTO reqDTO, HttpServletResponse httpServletResponse) {
        if (ObjectUtil.isEmpty(reqDTO.getStartTime()) && ObjectUtil.isEmpty(reqDTO.getEndTime())) {
            //获取7天前的时间
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.DATE, -7);
            reqDTO.setStartTime(DateUtils.dateToLocalDateTime(calendar.getTime()));
        }

        //构建导出数据
        List<UserLoginLogDO> exportDatas = userLoginLogDao.selectExportData(reqDTO);
        List<LoginLogExcelBO> exportList = exportDatas.stream().map(UserLoginLogServiceImpl::buildLoginLogExcelBO).collect(Collectors.toList());

        //构建流
        ExportParams exportParams = new ExportParams();
        exportParams.setSheetName("登录日志数据");
        exportParams.setType(ExcelType.XSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, LoginLogExcelBO.class, exportList);
        httpServletResponse.setCharacterEncoding("UTF-8");
        try {
            httpServletResponse.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("loginLog" + ".xlsx", "UTF-8"));
            httpServletResponse.setHeader("content-type", "application/vnd.ms-excel");
            workbook.write(httpServletResponse.getOutputStream());
        } catch (Exception e) {
            log.error("export loginLog excel file fail....", e);
            throw new CommonException(CommonErrorEnum.ERROR_EXPORT_FILE);
        }
    }

    private static LoginLogExcelBO buildLoginLogExcelBO(UserLoginLogDO item) {
        LoginLogExcelBO logExcelBO = new LoginLogExcelBO();
        logExcelBO.setUseAccount(item.getUserAccount());
        logExcelBO.setIpAddress(item.getIpAddress());
        logExcelBO.setBrowserType(item.getBrowserType());
        logExcelBO.setSystemType(item.getSystemType());
        logExcelBO.setStatus(item.getStatus());
        logExcelBO.setLoginTime(DateUtils.localDateTimeToStr(item.getLoginTime(), DateUtils.DEFAULT_FORMAT));
        return logExcelBO;
    }
}




